<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>论文写作大师 4.0</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/docx@7.8.2/build/index.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        :root {
            --primary-color: #4a6bff;
            --secondary-color: #6c757d;
            --accent-color: #00c9a7;
            --dark-color: #2c3e50;
            --light-color: #f8f9fa;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --info-color: #17a2b8;
        }
        
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background-color: #f5f7fa;
            color: var(--dark-color);
            line-height: 1.8;
        }
        
        .app-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
            color: white;
            padding: 25px 0;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
            z-index: -1;
        }
        
        .header h1 {
            margin: 0;
            font-weight: 800;
            font-size: 2.5rem;
            letter-spacing: 1px;
        }
        
        .header p {
            margin: 10px 0 0;
            opacity: 0.9;
            font-size: 1.1rem;
        }
        
        .feature-card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            height: 100%;
            background-color: white;
            overflow: hidden;
            position: relative;
        }
        
        .feature-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        .feature-icon {
            font-size: 2.8rem;
            color: var(--primary-color);
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .feature-card:hover .feature-icon {
            transform: scale(1.1);
            color: var(--accent-color);
        }
        
        .nav-tabs {
            border-bottom: 2px solid rgba(0, 0, 0, 0.05);
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: var(--secondary-color);
            font-weight: 600;
            padding: 12px 25px;
            transition: all 0.3s ease;
            border-radius: 8px 8px 0 0;
            margin-right: 5px;
            font-size: 0.95rem;
        }
        
        .nav-tabs .nav-link:hover {
            color: var(--primary-color);
            background-color: rgba(74, 107, 255, 0.05);
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            border-bottom: 3px solid var(--primary-color);
            background-color: transparent;
        }
        
        .tab-content {
            padding: 30px 0;
        }
        
        .chat-container {
            height: 500px;
            overflow-y: auto;
            padding: 15px;
            background-color: white;
            border-radius: 12px;
            margin-bottom: 15px;
            border: 1px solid rgba(0, 0, 0, 0.05);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
        }
        
        .message {
            padding: 12px 18px;
            border-radius: 12px;
            margin-bottom: 12px;
            max-width: 85%;
            word-wrap: break-word;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            line-height: 1.6;
            font-size: 0.95rem;
        }
        
        .user-message {
            background-color: #f0f5ff;
            margin-left: auto;
            border: 1px solid #d6e4ff;
            color: var(--dark-color);
        }
        
        .ai-message {
            background-color: white;
            margin-right: auto;
            border: 1px solid #e9ecef;
            color: var(--dark-color);
        }
        
        .loading-spinner {
            display: none;
        }
        
        .text-area-container {
            display: flex;
            gap: 25px;
            margin-bottom: 25px;
        }
        
        .text-area-box {
            flex: 1;
            min-width: 0;
        }
        
        .text-area-box h5 {
            margin-bottom: 15px;
            color: var(--dark-color);
            font-weight: 600;
            display: flex;
            align-items: center;
        }
        
        .text-area-box h5 i {
            margin-right: 8px;
            color: var(--primary-color);
        }
        
        .text-area-box textarea {
            height: 300px;
            resize: none;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 15px;
            font-size: 0.95rem;
            line-height: 1.6;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
        }
        
        .text-area-box textarea:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 107, 255, 0.15);
            outline: none;
        }
        
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .result-card {
            background-color: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            margin-top: 25px;
        }
        
        .progress-container {
            margin: 20px 0;
            display: none;
        }
        
        .formatted-paper {
            background-color: white;
            padding: 35px;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            font-family: "Times New Roman", "SimSun", serif;
            line-height: 1.8;
            font-size: 16px;
        }
        
        .formatted-paper h1 {
            font-size: 22px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .formatted-paper h2 {
            font-size: 18px;
            font-weight: bold;
            margin-top: 30px;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 1px solid #eee;
        }
        
        .formatted-paper h3 {
            font-size: 16px;
            font-weight: bold;
            margin-top: 25px;
            margin-bottom: 10px;
        }
        
        .formatted-paper p {
            margin-bottom: 15px;
            text-align: justify;
            text-indent: 2em;
            line-height: 1.8;
        }
        
        .formatted-paper table {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            font-size: 14px;
            font-family: Arial, sans-serif;
            table-layout: auto;
            word-break: break-word;
        }
        
        .formatted-paper table caption {
            font-style: italic;
            text-align: center;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .formatted-paper table thead tr {
            border-bottom: 2px solid var(--primary-color);
            background-color: #f8f9fa;
        }
        
        .formatted-paper table th {
            padding: 12px 15px;
            text-align: left;
            font-weight: bold;
            vertical-align: middle;
            background-color: #f8f9fa;
        }
        
        .formatted-paper table tbody tr {
            border-bottom: 1px solid #e9ecef;
        }
        
        .formatted-paper table tbody tr:last-of-type {
            border-bottom: 2px solid var(--primary-color);
        }
        
        .formatted-paper table td {
            padding: 12px 15px;
            vertical-align: middle;
            text-align: left;
        }
        
        .formatted-paper .paper-section {
            margin-bottom: 35px;
            padding-bottom: 25px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .formatted-paper .paper-section:last-child {
            border-bottom: none;
        }
        
        .formatted-paper .paper-title {
            text-align: center;
            font-size: 20px;
            margin-bottom: 10px;
            font-weight: bold;
        }
        
        .formatted-paper .paper-author {
            text-align: center;
            font-style: italic;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .formatted-paper .paper-abstract {
            background-color: #f9f9f9;
            padding: 20px;
            border-left: 3px solid var(--primary-color);
            margin-bottom: 25px;
            font-size: 14px;
            line-height: 1.8;
        }
        
        .formatted-paper .paper-keywords {
            font-style: italic;
            margin-bottom: 25px;
            font-size: 14px;
        }
        
        .formatted-paper .paper-reference {
            padding-left: 25px;
            text-indent: -25px;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .formatted-paper .paper-figure {
            text-align: center;
            margin: 25px 0;
            padding: 15px;
            background-color: #f9f9f9;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
        }
        
        .formatted-paper .paper-figure img {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 0 auto;
        }
        
        .formatted-paper .paper-figure-caption {
            font-style: italic;
            margin-top: 10px;
            text-align: center;
            font-size: 14px;
        }
        
        .export-buttons {
            margin-top: 25px;
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .rewrite-options {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
        }
        
        .rewrite-option-item {
            margin-bottom: 12px;
            display: flex;
            align-items: center;
        }
        
        .rewrite-option-item input {
            margin-right: 8px;
        }
        
        .rewrite-option-item label {
            margin-left: 5px;
            font-size: 0.95rem;
        }
        
        .rewrite-preview {
            display: flex;
            gap: 25px;
            margin-top: 25px;
        }
        
        .rewrite-preview-box {
            flex: 1;
            border: 1px solid #e0e0e0;
            padding: 20px;
            border-radius: 10px;
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
        }
        
        .rewrite-preview-box h5 {
            margin-top: 0;
            padding-bottom: 12px;
            border-bottom: 1px solid #eee;
            color: var(--dark-color);
            font-weight: 600;
        }
        
        .highlight-original {
            background-color: #fff3e0;
            padding: 2px;
            border-radius: 3px;
        }
        
        .highlight-rewritten {
            background-color: #e8f5e9;
            padding: 2px;
            border-radius: 3px;
        }
        
        .diff-container {
            margin-top: 25px;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
        }
        
        .diff-line {
            margin-bottom: 6px;
            padding: 6px;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            border-radius: 4px;
        }
        
        .diff-added {
            background-color: #e8f5e9;
        }
        
        .diff-removed {
            background-color: #ffebee;
        }
        
        .diff-unchanged {
            background-color: #f8f9fa;
        }
        
        .template-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .template-btn {
            font-size: 0.85rem;
            padding: 6px 12px;
            border-radius: 20px;
        }
        
        .history-item {
            padding: 10px 15px;
            margin-bottom: 8px;
            background-color: #f8f9fa;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            border-left: 3px solid transparent;
        }
        
        .history-item:hover {
            background-color: #e9ecef;
            border-left: 3px solid var(--primary-color);
        }
        
        .history-container {
            max-height: 250px;
            overflow-y: auto;
            margin-bottom: 20px;
            border: 1px solid #eee;
            padding: 15px;
            border-radius: 10px;
            background-color: white;
        }
        
        .btn {
            padding: 8px 18px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .btn i {
            font-size: 1.1rem;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: #3a5bef;
            border-color: #3a5bef;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(74, 107, 255, 0.3);
        }
        
        .btn-outline-primary {
            color: var(--primary-color);
            border-color: var(--primary-color);
            background-color: transparent;
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #5a6268;
            border-color: #5a6268;
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
            color: white;
        }
        
        .btn-info {
            background-color: var(--info-color);
            border-color: var(--info-color);
            color: white;
        }
        
        .btn-warning {
            background-color: var(--warning-color);
            border-color: var(--warning-color);
            color: var(--dark-color);
        }
        
        .btn-danger {
            background-color: var(--danger-color);
            border-color: var(--danger-color);
            color: white;
        }
        
        /* 新增的文献验证样式 */
        .reference-item {
            padding: 15px;
            margin-bottom: 15px;
            border-left: 3px solid #ddd;
            transition: all 0.3s;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
        }
        
        .reference-item.verified {
            border-left-color: var(--success-color);
            background-color: rgba(40, 167, 69, 0.05);
        }
        
        .reference-item.unverified {
            border-left-color: var(--danger-color);
            background-color: rgba(220, 53, 69, 0.05);
        }
        
        .reference-item .verify-btn {
            margin-left: 10px;
            font-size: 0.85rem;
            padding: 4px 8px;
        }
        
        .reference-item .doi-link {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
        }
        
        .reference-item .doi-link:hover {
            text-decoration: underline;
        }
        
        .reference-item .source-badge {
            font-size: 0.75rem;
            margin-left: 8px;
            padding: 4px 8px;
        }
        
        /* 导出进度条样式 */
        .export-progress {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }
        
        .export-progress-content {
            background-color: white;
            padding: 30px;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .export-progress-bar {
            height: 10px;
            margin-top: 20px;
            border-radius: 5px;
            overflow: hidden;
            background-color: #f1f1f1;
        }
        
        .export-progress-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
            width: 0%;
            transition: width 0.3s;
        }
        
        /* 卡片样式 */
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 25px;
            overflow: hidden;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 15px 20px;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        .card-body {
            padding: 25px;
        }
        
        /* 表单样式 */
        .form-control, .form-select {
            border-radius: 8px;
            padding: 10px 15px;
            border: 1px solid #e0e0e0;
            transition: all 0.3s;
            box-shadow: none;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 107, 255, 0.15);
        }
        
        /* 警告框样式 */
        .alert {
            border-radius: 8px;
            padding: 15px;
            border: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }
        
        .alert i {
            margin-right: 8px;
        }
        
        /* 大纲样式 */
        .outline-container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 25px;
        }
        
        .outline-item {
            padding: 12px 15px;
            margin-bottom: 10px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border-left: 3px solid var(--primary-color);
            transition: all 0.3s;
        }
        
        .outline-item:hover {
            background-color: #e9ecef;
            transform: translateX(5px);
        }
        
        .outline-item h5 {
            margin: 0;
            font-size: 1rem;
            font-weight: 600;
            color: var(--dark-color);
        }
        
        .outline-item p {
            margin: 5px 0 0;
            color: var(--secondary-color);
            font-size: 0.9rem;
        }
        
        /* 响应式设计 */
        @media (max-width: 992px) {
            .header h1 {
                font-size: 2rem;
            }
            
            .header p {
                font-size: 1rem;
            }
            
            .text-area-container {
                flex-direction: column;
            }
            
            .rewrite-preview {
                flex-direction: column;
            }
        }
        
        @media (max-width: 768px) {
            .app-container {
                padding: 15px;
            }
            
            .header {
                padding: 20px 0;
            }
            
            .header h1 {
                font-size: 1.8rem;
            }
            
            .nav-tabs .nav-link {
                padding: 10px 15px;
                font-size: 0.9rem;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
            }
            
            .template-buttons {
                flex-direction: column;
            }
            
            .formatted-paper {
                padding: 20px;
            }
        }
        
        @media (max-width: 576px) {
            .header h1 {
                font-size: 1.5rem;
            }
            
            .feature-icon {
                font-size: 2.2rem;
            }
            
            .formatted-paper {
                padding: 15px;
                font-size: 14px;
            }
            
            .formatted-paper h1 {
                font-size: 18px;
            }
            
            .formatted-paper h2 {
                font-size: 16px;
            }
            
            .formatted-paper h3 {
                font-size: 15px;
            }
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease forwards;
        }
        
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header text-center">
            <h1><i class="bi bi-journal-text"></i> 论文写作大师 4.0</h1>
            <p>永发独创高阶版</p>
        </div>
        
        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab">首页</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="ai-tab" data-bs-toggle="tab" data-bs-target="#ai" type="button" role="tab">论文大师</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="outline-tab" data-bs-toggle="tab" data-bs-target="#outline" type="button" role="tab">论文大纲</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="rewrite-tab" data-bs-toggle="tab" data-bs-target="#rewrite" type="button" role="tab">论文降重</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="polish-tab" data-bs-toggle="tab" data-bs-target="#polish" type="button" role="tab">论文润色</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="proposal-tab" data-bs-toggle="tab" data-bs-target="#proposal" type="button" role="tab">开题报告</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="reference-tab" data-bs-toggle="tab" data-bs-target="#reference" type="button" role="tab">文献管理</button>
            </li>
        </ul>
        
        <div class="tab-content" id="myTabContent">
            <!-- 首页 -->
            <div class="tab-pane fade show active" id="home" role="tabpanel">
                <h2 class="mb-4">欢迎使用论文写作大师 4.0</h2>
                <p class="lead">专业的论文写作工具，为您提供从写作到修改的一站式服务</p>
                
                <div class="row mt-5">
                    <div class="col-md-4 mb-4">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon">
                                    <i class="bi bi-robot"></i>
                                </div>
                                <h5 class="card-title">论文写作大师</h5>
                                <p class="card-text">基于论文大师的强大写作能力，帮助您快速创作结构完整的论文内容。</p>
                                <button class="btn btn-primary" onclick="switchTab('ai')">开始使用</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon">
                                    <i class="bi bi-list-check"></i>
                                </div>
                                <h5 class="card-title">论文大纲</h5>
                                <p class="card-text">根据论文题目和研究方向，生成专业完整的论文大纲结构。</p>
                                <button class="btn btn-primary" onclick="switchTab('outline')">开始使用</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon">
                                    <i class="bi bi-pencil-square"></i>
                                </div>
                                <h5 class="card-title">论文降重</h5>
                                <p class="card-text">智能改写论文内容，有效降低重复率，保持原意不变。</p>
                                <button class="btn btn-primary" onclick="switchTab('rewrite')">开始使用</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-4 mb-4">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon">
                                    <i class="bi bi-magic"></i>
                                </div>
                                <h5 class="card-title">论文润色</h5>
                                <p class="card-text">提升论文语言质量，使表达更加专业、流畅、学术化。</p>
                                <button class="btn btn-primary" onclick="switchTab('polish')">开始使用</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon">
                                    <i class="bi bi-file-earmark-text"></i>
                                </div>
                                <h5 class="card-title">开题报告</h5>
                                <p class="card-text">根据题目和方向自动生成完整的开题报告框架。</p>
                                <button class="btn btn-primary" onclick="switchTab('proposal')">开始使用</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon">
                                    <i class="bi bi-book"></i>
                                </div>
                                <h5 class="card-title">文献管理</h5>
                                <p class="card-text">查找、验证和管理参考文献，确保引用真实可靠。</p>
                                <button class="btn btn-primary" onclick="switchTab('reference')">开始使用</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-4">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-lightbulb"></i> 使用指南</h5>
                        <ol>
                            <li>选择您需要的功能：大师写作、论文大纲、论文降重、论文润色或开题报告</li>
                            <li>输入您的论文内容或写作要求</li>
                            <li>点击相应按钮获取大师的结果</li>
                            <li>在预览区域查看格式化后的论文</li>
                            <li>导出Word文档获得最终成果</li>
                        </ol>
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> 提示：所有功能均可无限次使用，支持5000字、8000字和10000字以上论文写作！
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- AI写作助手 -->
            <div class="tab-pane fade" id="ai" role="tabpanel">
                <h2 class="mb-4"><i class="bi bi-robot"></i>论文写作大师</h2>
                <p>与大师对话获取论文写作建议，可以要求大师帮助撰写论文的任何部分。</p>
                
                <div class="row mb-3">
                    <div class="col-md-4">
                        <label class="form-label">论文类型</label>
                        <select id="paper-type" class="form-select">
                            <option value="research">研究论文</option>
                            <option value="review">综述论文</option>
                            <option value="thesis">学位论文</option>
                            <option value="case-study">案例研究</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">字数要求</label>
                        <select id="word-count" class="form-select">
                            <option value="5000">5000字左右</option>
                            <option value="8000">8000字左右</option>
                            <option value="10000">10000字以上</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">学科领域</label>
                        <select id="paper-field" class="form-select">
                            <option value="general">通用</option>
                            <option value="science">自然科学</option>
                            <option value="engineering">工程技术</option>
                            <option value="medicine">医学</option>
                            <option value="humanities">人文社科</option>
                            <option value="economics">经济学</option>
                            <option value="law">法学</option>
                            <option value="education">教育学</option>
                            <option value="arts">艺术学</option>
                        </select>
                    </div>
                </div>
                
                <div class="template-buttons">
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('introduction')">插入引言模板</button>
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('methodology')">插入方法模板</button>
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('results')">插入结果模板</button>
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('discussion')">插入讨论模板</button>
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('conclusion')">插入结论模板</button>
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('abstract')">插入摘要模板</button>
                    <button class="btn btn-outline-secondary template-btn" onclick="insertTemplate('references')">插入参考文献模板</button>
                </div>
                
                <div class="chat-container" id="ai-chat-container">
                    <div class="message ai-message">
                        <strong>论文写作大师:</strong> 您好！我是论文写作大师，可以帮助您撰写结构完整、内容充实的学术论文。请告诉我您需要撰写的论文主题和具体要求。
                    </div>
                </div>
                
                <div class="input-group mb-3">
                    <textarea id="ai-input" class="form-control" rows="3" placeholder="请输入您的论文写作需求，例如：'请帮我写一篇关于人工智能在医疗领域应用的研究论文，要求包含引言、文献综述、方法、结果和讨论部分...'"></textarea>
                </div>
                
                <div class="progress-container" id="progress-container">
                    <div class="progress">
                        <div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div class="text-center mt-2" id="progress-text">别打扰我创作，还请稍等..</div>
                </div>
                
                <div class="d-flex justify-content-between">
                    <button class="btn btn-outline-secondary" onclick="clearChat()">
                        <i class="bi bi-trash"></i> 清空对话
                    </button>
                    <button id="ai-send-btn" class="btn btn-primary" onclick="sendAIRequest()">
                        <span id="ai-send-text">发送</span>
                        <span id="ai-loading-spinner" class="loading-spinner">
                            <i class="bi bi-arrow-repeat"></i> 创作中...
                        </span>
                    </button>
                </div>
                
                <div class="card mt-4">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-lightbulb"></i> 使用技巧</h5>
                        <ul>
                            <li>明确告诉大师您需要撰写的论文类型和具体部分</li>
                            <li>提供详细的关键词和研究方向</li>
                            <li>可以要求AI按照特定结构组织内容</li>
                            <li>使用"继续"或"扩展"命令让AI补充更多内容</li>
                            <li>使用上方模板按钮快速插入常用结构</li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <!-- 论文大纲 -->
            <div class="tab-pane fade" id="outline" role="tabpanel">
                <h2 class="mb-4"><i class="bi bi-list-check"></i> 论文大纲生成</h2>
                <p>根据论文题目和研究方向，生成专业完整的论文大纲结构。</p>
                
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">基本信息</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="outline-title" class="form-label">论文题目</label>
                                    <input type="text" id="outline-title" class="form-control" placeholder="请输入论文题目">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="outline-field" class="form-label">研究方向</label>
                                    <input type="text" id="outline-field" class="form-control" placeholder="请输入研究方向">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="outline-type" class="form-label">论文类型</label>
                                    <select id="outline-type" class="form-select">
                                        <option value="research">研究论文</option>
                                        <option value="review">综述论文</option>
                                        <option value="thesis">学位论文</option>
                                        <option value="case-study">案例研究</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="outline-words" class="form-label">字数要求</label>
                                    <select id="outline-words" class="form-select">
                                        <option value="5000">5000字左右</option>
                                        <option value="8000">8000字左右</option>
                                        <option value="10000">10000字以上</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="outline-keywords" class="form-label">关键词（用逗号分隔）</label>
                            <input type="text" id="outline-keywords" class="form-control" placeholder="例如：人工智能,机器学习,深度学习">
                        </div>
                        
                        <div class="mb-3">
                            <label for="outline-requirements" class="form-label">特殊要求</label>
                            <textarea id="outline-requirements" class="form-control" rows="3" placeholder="请描述您对论文大纲的特殊要求（可选）"></textarea>
                        </div>
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button id="generate-outline-btn" class="btn btn-primary" onclick="generateOutline()">
                        <span id="outline-text">创作论文大纲</span>
                        <span id="outline-spinner" class="loading-spinner">
                            <i class="bi bi-arrow-repeat"></i> 创作中...
                        </span>
                    </button>
                    <button class="btn btn-outline-secondary" onclick="clearOutlineForm()">
                        <i class="bi bi-trash"></i> 清空表单
                    </button>
                </div>
                
                <div class="outline-container mt-4" id="outline-result" style="display: none;">
                    <h4 class="mb-4">论文大纲结构</h4>
                    <div id="outline-content"></div>
                    
                    <div class="export-buttons mt-4">
                        <button class="btn btn-outline-primary" onclick="exportOutlineAsDOCX()">
                            <i class="bi bi-file-earmark-word"></i> 导出Word
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 论文降重 -->
            <div class="tab-pane fade" id="rewrite" role="tabpanel">
                <h2 class="mb-4"><i class="bi bi-pencil-square"></i> 论文降重</h2>
                <p>输入需要降重的文本，大师将智能改写内容以降低重复率，同时保持原意不变。</p>
                
                <div class="rewrite-options">
                    <h5><i class="bi bi-gear"></i> 降重选项</h5>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="rewrite-option-item">
                                <input type="checkbox" id="option-synonym" checked>
                                <label for="option-synonym">同义词替换</label>
                            </div>
                            <div class="rewrite-option-item">
                                <input type="checkbox" id="option-structure" checked>
                                <label for="option-structure">结构调整</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="rewrite-option-item">
                                <input type="checkbox" id="option-paraphrase" checked>
                                <label for="option-paraphrase">意译改写</label>
                            </div>
                            <div class="rewrite-option-item">
                                <input type="checkbox" id="option-explain" checked>
                                <label for="option-explain">增加解释</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="rewrite-option-item">
                                <input type="checkbox" id="option-academic" checked>
                                <label for="option-academic">学术化表达</label>
                            </div>
                            <div class="rewrite-option-item">
                                <input type="checkbox" id="option-merge" checked>
                                <label for="option-merge">合并/拆分句子</label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="text-area-container">
                    <div class="text-area-box">
                        <h5><i class="bi bi-file-text"></i> 原文</h5>
                        <textarea id="original-text" class="form-control" placeholder="请输入需要降重的文本..."></textarea>
                    </div>
                    <div class="text-area-box">
                        <h5><i class="bi bi-file-earmark-text"></i> 降重结果</h5>
                        <textarea id="rewritten-text" class="form-control" placeholder="降重结果将显示在这里..." readonly></textarea>
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button id="rewrite-btn" class="btn btn-primary" onclick="rewriteText()">
                        <span id="rewrite-text">智能降重</span>
                        <span id="rewrite-spinner" class="loading-spinner">
                            <i class="bi bi-arrow-repeat"></i> 处理中...
                        </span>
                    </button>
                    <button class="btn btn-secondary" onclick="copyRewrittenText()">
                        <i class="bi bi-clipboard"></i> 复制结果
                    </button>
                    <button class="btn btn-outline-secondary" onclick="clearRewriteText()">
                        <i class="bi bi-trash"></i> 清空
                    </button>
                    <button class="btn btn-info" onclick="showRewriteDiff()">
                        <i class="bi bi-file-diff"></i> 查看差异
                    </button>
                </div>
                
                <div class="rewrite-preview" id="rewrite-preview" style="display: none;">
                    <div class="rewrite-preview-box">
                        <h5><i class="bi bi-file-text"></i> 原文</h5>
                        <div id="original-preview"></div>
                    </div>
                    <div class="rewrite-preview-box">
                        <h5><i class="bi bi-file-earmark-text"></i> 降重后</h5>
                        <div id="rewritten-preview"></div>
                    </div>
                </div>
                
                <div class="diff-container" id="rewrite-diff" style="display: none;">
                    <h5><i class="bi bi-file-diff"></i> 修改对比</h5>
                    <div id="diff-content"></div>
                </div>
                
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title"><i class="bi bi-lightbulb"></i> 降重原理</h5>
                        <p>大师会使用以下方法降低文本重复率：</p>
                        <ul>
                            <li>同义词替换 - 使用专业同义词替换原有词汇</li>
                            <li>结构调整 - 改变句子结构和段落组织方式</li>
                            <li>意译改写 - 用不同表达方式传达相同意思</li>
                            <li>增加解释 - 补充说明性内容增强原创性</li>
                            <li>学术化表达 - 提升语言的专业性和学术性</li>
                            <li>合并/拆分句子 - 优化句子长度和复杂度</li>
                        </ul>
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle"></i> 请注意：降重后请务必检查内容是否准确表达了原意！
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 论文润色 -->
            <div class="tab-pane fade" id="polish" role="tabpanel">
                <h2 class="mb-4"><i class="bi bi-magic"></i> 论文润色</h2>
                <p>提升论文语言质量，使表达更加专业、流畅、学术化。</p>
                
                <div class="text-area-container">
                    <div class="text-area-box">
                        <h5><i class="bi bi-file-text"></i> 原文</h5>
                        <textarea id="original-text-polish" class="form-control" placeholder="请输入需要润色的文本..."></textarea>
                    </div>
                    <div class="text-area-box">
                        <h5><i class="bi bi-file-earmark-text"></i> 润色结果</h5>
                        <textarea id="polished-text" class="form-control" placeholder="润色结果将显示在这里..." readonly></textarea>
                    </div>
                </div>
                
                <div class="row mb-3">
                    <div class="col-md-4">
                        <label class="form-label">润色风格</label>
                        <select id="polish-style" class="form-select">
                            <option value="academic">学术严谨</option>
                            <option value="concise">简洁明了</option>
                            <option value="formal">正式专业</option>
                            <option value="fluent">流畅自然</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">目标读者</label>
                        <select id="polish-audience" class="form-select">
                            <option value="general">普通读者</option>
                            <option value="expert">领域专家</option>
                            <option value="international">国际读者</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">学科领域</label>
                        <select id="polish-field" class="form-select">
                            <option value="general">通用</option>
                            <option value="science">自然科学</option>
                            <option value="engineering">工程技术</option>
                            <option value="medicine">医学</option>
                            <option value="humanities">人文社科</option>
                            <option value="economics">经济学</option>
                            <option value="law">法学</option>
                            <option value="education">教育学</option>
                            <option value="arts">艺术学</option>
                        </select>
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button id="polish-btn" class="btn btn-primary" onclick="polishText()">
                        <span id="polish-text">开始润色</span>
                        <span id="polish-spinner" class="loading-spinner">
                            <i class="bi bi-arrow-repeat"></i> 处理中...
                        </span>
                    </button>
                    <button class="btn btn-secondary" onclick="copyPolishedText()">
                        <i class="bi bi-clipboard"></i> 复制结果
                    </button>
                    <button class="btn btn-outline-secondary" onclick="clearPolishText()">
                        <i class="bi bi-trash"></i> 清空
                    </button>
                </div>
                
                <div class="result-card" id="polish-suggestions" style="display: none;">
                    <h5><i class="bi bi-chat-square-text"></i> 润色建议</h5>
                    <div id="suggestions-content"></div>
                </div>
            </div>
            
            <!-- 开题报告 -->
            <div class="tab-pane fade" id="proposal" role="tabpanel">
                <h2 class="mb-4"><i class="bi bi-file-earmark-text"></i> 开题报告生成</h2>
                <p>根据您的研究题目和方向，自动生成完整的开题报告框架。</p>
                
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">基本信息</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="proposal-title" class="form-label">论文题目</label>
                                    <input type="text" id="proposal-title" class="form-control" placeholder="请输入论文题目">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="proposal-author" class="form-label">作者姓名</label>
                                    <input type="text" id="proposal-author" class="form-control" placeholder="请输入作者姓名">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="proposal-school" class="form-label">学校/机构</label>
                                    <input type="text" id="proposal-school" class="form-control" placeholder="请输入学校或机构名称">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="proposal-major" class="form-label">专业方向</label>
                                    <input type="text" id="proposal-major" class="form-control" placeholder="请输入专业方向">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="proposal-supervisor" class="form-label">指导教师</label>
                                    <input type="text" id="proposal-supervisor" class="form-control" placeholder="请输入指导教师姓名">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="proposal-date" class="form-label">预计完成日期</label>
                                    <input type="date" id="proposal-date" class="form-control">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">研究内容</h5>
                        <div class="mb-3">
                            <label for="proposal-background" class="form-label">研究背景与意义</label>
                            <textarea id="proposal-background" class="form-control" rows="3" placeholder="简要描述研究背景、现状和研究意义"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="proposal-objective" class="form-label">研究目标</label>
                            <textarea id="proposal-objective" class="form-control" rows="3" placeholder="明确研究的主要目标和预期成果"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="proposal-content" class="form-label">研究内容</label>
                            <textarea id="proposal-content" class="form-control" rows="3" placeholder="详细描述研究的具体内容和方法"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="proposal-innovation" class="form-label">创新点</label>
                            <textarea id="proposal-innovation" class="form-control" rows="3" placeholder="说明本研究的创新之处"></textarea>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">研究方法与技术路线</h5>
                        <div class="mb-3">
                            <label for="proposal-method" class="form-label">研究方法</label>
                            <textarea id="proposal-method" class="form-control" rows="3" placeholder="描述拟采用的研究方法和技术"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="proposal-plan" class="form-label">研究计划</label>
                            <textarea id="proposal-plan" class="form-control" rows="3" placeholder="详细说明研究的时间安排和进度计划"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="proposal-reference" class="form-label">参考文献</label>
                            <textarea id="proposal-reference" class="form-control" rows="3" placeholder="列出主要参考文献（可自动补充）"></textarea>
                        </div>
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button id="generate-proposal-btn" class="btn btn-primary" onclick="generateProposal()">
                        <span id="proposal-text">创作开题报告</span>
                        <span id="proposal-spinner" class="loading-spinner">
                            <i class="bi bi-arrow-repeat"></i> 创作中...
                        </span>
                    </button>
                    <button class="btn btn-outline-secondary" onclick="clearProposalForm()">
                        <i class="bi bi-trash"></i> 清空表单
                    </button>
                </div>
                
                <div class="card mt-4" id="proposal-result" style="display: none;">
                    <div class="card-body">
                        <h5 class="card-title">开题报告结果</h5>
                        <div id="proposal-content-result"></div>
                        
                        <div class="export-buttons mt-3">
                            <button class="btn btn-outline-primary" onclick="exportProposalAsDOCX()">
                                <i class="bi bi-file-earmark-word"></i> 导出Word
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 文献管理 -->
            <div class="tab-pane fade" id="reference" role="tabpanel">
                <h2 class="mb-4"><i class="bi bi-book"></i> 文献管理</h2>
                <p>查找、验证和管理参考文献，确保引用真实可靠。</p>
                
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">文献搜索</h5>
                        <div class="input-group mb-3">
                            <input type="text" id="reference-search" class="form-control" placeholder="输入文献标题、作者或关键词">
                            <button class="btn btn-primary" type="button" id="search-reference-btn" onclick="searchReferences()">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <label class="form-label">数据库</label>
                                <select id="reference-database" class="form-select">
                                    <option value="crossref">CrossRef</option>
                                    <option value="google-scholar">Google Scholar</option>
                                    <option value="pubmed">PubMed</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">引用格式</label>
                                <select id="reference-style" class="form-select">
                                    <option value="apa">APA</option>
                                    <option value="mla">MLA</option>
                                    <option value="chicago">Chicago</option>
                                    <option value="gb">GB/T 7714</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">搜索结果</h5>
                        <div id="reference-search-results" style="max-height: 400px; overflow-y: auto;">
                            <p class="text-muted">搜索结果将显示在这里</p>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">我的文献库</h5>
                        <div id="reference-library">
                            <p class="text-muted">您添加的文献将显示在这里</p>
                        </div>
                        
                        <div class="mt-3">
                            <button class="btn btn-primary" onclick="exportReferences()">
                                <i class="bi bi-download"></i> 导出参考文献
                            </button>
                            <button class="btn btn-outline-secondary" onclick="clearReferences()">
                                <i class="bi bi-trash"></i> 清空文献库
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 论文预览和导出区域 -->
        <div class="card mt-4" id="paper-preview-section" style="display: none;">
            <div class="card-body">
                <h5 class="card-title">论文预览与导出</h5>
                <div class="formatted-paper" id="formatted-paper">
                    <!-- 这里将显示格式化后的论文内容 -->
                </div>
                
                <div class="export-buttons">
                    <button class="btn btn-outline-primary" onclick="exportAsDOCX()">
                        <i class="bi bi-file-earmark-word"></i> 导出Word
                    </button>
                    <button class="btn btn-outline-primary" onclick="copyToClipboard()">
                        <i class="bi bi-clipboard"></i> 复制内容
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 导出进度条 -->
    <div class="export-progress" id="export-progress">
        <div class="export-progress-content">
            <h5>正在导出Word文档</h5>
            <p id="export-progress-text">准备导出内容...</p>
            <div class="export-progress-bar">
                <div class="export-progress-fill" id="export-progress-fill"></div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // DeepSeek API配置
        const DEEPSEEK_API_KEY = "sk-ce6e5b19ea114b4fb5b929589c81bac2";
        const DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
        
        // 文献API配置
        const CROSSREF_API_URL = "https://api.crossref.org/works";
        const GOOGLE_SCHOLAR_API_URL = "https://serpapi.com/search.json";
        const PUBMED_API_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
        const PUBMED_SUMMARY_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi";
        
        // 全局变量
        let chatHistory = [
            {
                role: "assistant",
                content: "您好！我是论文写作助手，可以帮助您撰写结构完整、内容充实的学术论文。请告诉我您需要撰写的论文主题和具体要求。"
            }
        ];
        let currentPaperContent = "";
        let lastOriginalText = "";
        let lastRewrittenText = "";
        let isExporting = false;
        let writingHistory = [];
        let references = [];
        
        // 切换标签页
        function switchTab(tabId) {
            const tab = document.getElementById(`${tabId}-tab`);
            const tabInstance = new bootstrap.Tab(tab);
            tabInstance.show();
        }
        
        // 显示导出区域
        function showExportSection() {
            if (currentPaperContent) {
                showFormattedPaper(currentPaperContent);
            } else {
                alert("请先使用大师写作、降重或润色功能生成论文内容");
            }
        }
        
        // ========== AI写作助手功能 ==========
        function renderChat() {
            const container = document.getElementById('ai-chat-container');
            container.innerHTML = '';
            
            chatHistory.forEach(message => {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${message.role === 'user' ? 'user-message' : 'ai-message'} fade-in`;
                messageDiv.innerHTML = `<strong>${message.role === 'user' ? '你' : 'AI助手'}:</strong> ${message.content}`;
                container.appendChild(messageDiv);
            });
            
            // 滚动到底部
            container.scrollTop = container.scrollHeight;
        }
        
        function updateProgress(percentage) {
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');
            progressBar.style.width = `${percentage}%`;
            
            if (percentage < 100) {
                progressText.textContent = `正在创作论文内容 (${percentage}%)...`;
            } else {
                progressText.textContent = "内容生成完成！";
                setTimeout(() => {
                    document.getElementById('progress-container').style.display = 'none';
                }, 1000);
            }
        }
        
        // 插入论文模板
        function insertTemplate(templateType) {
            const templates = {
                'introduction': "本研究旨在探讨[研究主题]。近年来，[相关领域]发展迅速，但[研究空白]。本研究将[研究方法]，以期[研究目标]。",
                'methodology': "本研究采用[研究方法]。首先，[步骤1]；其次，[步骤2]；最后，[步骤3]。数据收集使用[工具/方法]，分析采用[分析方法]。",
                'results': "研究结果显示，[主要发现1]。具体而言，[详细数据1]。此外，[主要发现2]，表明[结论]。",
                'discussion': "本研究结果表明，[主要结论]。这与[前人研究]的结果一致/不同，可能原因是[解释]。本研究的意义在于[研究意义]。",
                'conclusion': "综上所述，本研究[总结发现]。主要贡献包括[贡献1]和[贡献2]。未来研究可考虑[未来方向]。",
                'abstract': "[研究背景]。[研究目的]。[研究方法]。[主要结果]。[结论意义]。关键词：[关键词1]；[关键词2]；[关键词3]",
                'references': "1. 作者1, 作者2. (年份). 文章标题. 期刊名, 卷(期), 页码. DOI: \n2. 作者3. (年份). 书名. 出版社."
            };
            
            const input = document.getElementById('ai-input');
            input.value += templates[templateType] || '';
            input.focus();
        }
        
        async function sendAIRequest() {
            const input = document.getElementById('ai-input');
            const message = input.value.trim();
            const paperType = document.getElementById('paper-type').value;
            const wordCount = document.getElementById('word-count').value;
            const paperField = document.getElementById('paper-field').value;
            
            if (!message) {
                alert('请输入您的写作需求');
                return;
            }
            
            // 添加用户消息
            const userMessage = { role: 'user', content: message };
            chatHistory.push(userMessage);
            renderChat();
            
            // 清空输入框
            input.value = '';
            
            // 显示加载状态
            const sendBtn = document.getElementById('ai-send-btn');
            const sendText = document.getElementById('ai-send-text');
            const loadingSpinner = document.getElementById('ai-loading-spinner');
            
            sendText.style.display = 'none';
            loadingSpinner.style.display = 'inline-block';
            sendBtn.disabled = true;
            
            // 显示进度条
            const progressContainer = document.getElementById('progress-container');
            progressContainer.style.display = 'block';
            updateProgress(0);
            
            try {
                // 生成完整的论文内容
                const response = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: `你是一个专业的论文写作助手，正在撰写一篇${wordCount}字的${paperType}论文，学科领域是${getFieldDescription(paperField)}。请严格按照学术规范撰写一篇完整的论文，包括标题、摘要、引言、方法、结果、讨论、结论和参考文献等部分。确保内容充实、结构完整。`
                            },
                            {
                                role: "user",
                                content: `论文主题: ${message}\n\n请撰写一篇完整的论文，要求: 1. 专业严谨 2. 字数充足 3. 结构完整`
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 4000
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 检查响应数据结构
                if (!data.choices || !data.choices[0] || !data.choices[0].message) {
                    throw new Error("API返回的数据格式不正确");
                }
                
                const formattedContent = data.choices[0].message.content;
                currentPaperContent = formattedContent;
                
                // 将生成的内容添加到聊天记录
                const aiMessage = { 
                    role: 'assistant', 
                    content: formattedContent
                };
                chatHistory.push(aiMessage);
                renderChat();
                
                // 添加到历史记录
                addToHistory(message, formattedContent);
                
                // 显示格式化后的论文
                showFormattedPaper(formattedContent);
                
                updateProgress(100);
            } catch (error) {
                console.error('API请求错误:', error);
                updateProgress(0);
                
                // 添加错误消息到聊天记录
                const errorMessage = {
                    role: 'assistant',
                    content: `抱歉，处理您的请求时出错: ${error.message}`
                };
                chatHistory.push(errorMessage);
                renderChat();
                
                alert('请求失败，请检查控制台查看详细信息');
            } finally {
                // 恢复按钮状态
                sendText.style.display = 'inline-block';
                loadingSpinner.style.display = 'none';
                sendBtn.disabled = false;
            }
        }
        
        // 添加到历史记录
        function addToHistory(prompt, content) {
            const historyItem = {
                id: Date.now(),
                prompt: prompt,
                content: content.substring(0, 100) + '...',
                fullContent: content,
                timestamp: new Date().toLocaleString()
            };
            
            writingHistory.unshift(historyItem);
            if (writingHistory.length > 10) {
                writingHistory.pop();
            }
            
            // 可以在这里添加将历史记录保存到localStorage的代码
            // localStorage.setItem('writingHistory', JSON.stringify(writingHistory));
        }
        
        function getFieldDescription(field) {
            const fields = {
                'general': '通用',
                'science': '自然科学',
                'engineering': '工程技术',
                'medicine': '医学',
                'humanities': '人文社科',
                'economics': '经济学',
                'law': '法学',
                'education': '教育学',
                'arts': '艺术学'
            };
            return fields[field] || '通用';
        }
        
        function clearChat() {
            if (confirm('确定要清空对话历史吗？')) {
                chatHistory = [
                    {
                        role: "assistant",
                        content: "您好！我是论文写作大师，可以帮助您撰写结构完整、内容充实的学术论文。请告诉我您需要撰写的论文主题和具体要求。"
                    }
                ];
                renderChat();
                currentPaperContent = "";
                document.getElementById('paper-preview-section').style.display = 'none';
            }
        }
        
        // 按Enter键发送消息
        document.getElementById('ai-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendAIRequest();
            }
        });
        
        // ========== 论文大纲功能 ==========
        async function generateOutline() {
            const title = document.getElementById('outline-title').value.trim();
            const field = document.getElementById('outline-field').value.trim();
            const paperType = document.getElementById('outline-type').value;
            const wordCount = document.getElementById('outline-words').value;
            const keywords = document.getElementById('outline-keywords').value.trim();
            const requirements = document.getElementById('outline-requirements').value.trim();
            
            if (!title || !field) {
                alert('请输入论文题目和研究方向');
                return;
            }
            
            // 显示加载状态
            const outlineBtn = document.getElementById('generate-outline-btn');
            const outlineText = document.getElementById('outline-text');
            const outlineSpinner = document.getElementById('outline-spinner');
            
            outlineText.style.display = 'none';
            outlineSpinner.style.display = 'inline-block';
            outlineBtn.disabled = true;
            
            try {
                // 调用DeepSeek API生成大纲
                const response = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: `你是一个专业的学术导师，需要根据用户提供的信息生成一篇${wordCount}字的${paperType}论文大纲。大纲应包括各级标题和简要内容说明，结构完整，符合学术规范。`
                            },
                            {
                                role: "user",
                                content: `请根据以下信息生成论文大纲：
                                
论文题目: ${title}
研究方向: ${field}
关键词: ${keywords}
特殊要求: ${requirements || '无'}
                                `
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 2000
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 检查响应数据结构
                if (!data.choices || !data.choices[0] || !data.choices[0].message) {
                    throw new Error("API返回的数据格式不正确");
                }
                
                const outlineContent = data.choices[0].message.content;
                displayOutline(outlineContent);
                
                // 保存内容用于导出
                currentPaperContent = outlineContent;
                
                // 显示结果区域
                document.getElementById('outline-result').style.display = 'block';
                
                // 滚动到结果区域
                document.getElementById('outline-result').scrollIntoView({ behavior: 'smooth' });
            } catch (error) {
                console.error('生成论文大纲失败:', error);
                alert(`生成论文大纲失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                outlineText.style.display = 'inline-block';
                outlineSpinner.style.display = 'none';
                outlineBtn.disabled = false;
            }
        }
        
        function displayOutline(content) {
            const outlineContainer = document.getElementById('outline-content');
            outlineContainer.innerHTML = '';
            
            // 分割大纲内容为不同部分
            const sections = content.split(/\n\d+\.\s+/).filter(s => s.trim());
            
            sections.forEach((section, index) => {
                if (!section.trim()) return;
                
                // 提取标题和内容
                const titleMatch = section.match(/^(.*?)\n/);
                const title = titleMatch ? titleMatch[1] : section;
                const sectionContent = titleMatch ? section.substring(titleMatch[0].length) : '';
                
                const outlineItem = document.createElement('div');
                outlineItem.className = 'outline-item fade-in';
                
                outlineItem.innerHTML = `
                    <h5>${index + 1}. ${title}</h5>
                    ${sectionContent ? `<p>${sectionContent.replace(/\n/g, '<br>')}</p>` : ''}
                `;
                
                outlineContainer.appendChild(outlineItem);
            });
        }
        
        function clearOutlineForm() {
            document.getElementById('outline-title').value = '';
            document.getElementById('outline-field').value = '';
            document.getElementById('outline-keywords').value = '';
            document.getElementById('outline-requirements').value = '';
            document.getElementById('outline-result').style.display = 'none';
        }
        
        function exportOutlineAsDOCX() {
            if (!currentPaperContent) {
                alert('请先生成论文大纲');
                return;
            }
            
            // 使用主导出函数
            exportAsDOCX();
        }
        
        // ========== 论文降重功能 ==========
        function getRewriteOptions() {
            return {
                synonym: document.getElementById('option-synonym').checked,
                structure: document.getElementById('option-structure').checked,
                paraphrase: document.getElementById('option-paraphrase').checked,
                explain: document.getElementById('option-explain').checked,
                academic: document.getElementById('option-academic').checked,
                merge: document.getElementById('option-merge').checked
            };
        }
        
        function getRewritePrompt(options) {
            let prompt = "你是一个专业的论文改写助手，需要将用户提供的论文段落进行改写以降低重复率，同时保持原意不变。请使用以下方法进行改写：\n\n";
            
            if (options.synonym) prompt += "- 使用专业同义词替换原有词汇\n";
            if (options.structure) prompt += "- 改变句子结构和段落组织方式\n";
            if (options.paraphrase) prompt += "- 用不同表达方式传达相同意思\n";
            if (options.explain) prompt += "- 补充说明性内容增强原创性\n";
            if (options.academic) prompt += "- 提升语言的专业性和学术性\n";
            if (options.merge) prompt += "- 优化句子长度和复杂度\n";
            
            prompt += "\n改写后的文本应该更加流畅自然，学术性更强。请直接返回改写后的内容，不需要额外的解释或说明。";
            
            return prompt;
        }
        
        async function rewriteText() {
            const originalText = document.getElementById('original-text').value.trim();
            if (!originalText) {
                alert('请输入需要降重的文本');
                return;
            }
            
            const options = getRewriteOptions();
            const systemPrompt = getRewritePrompt(options);
            
            // 显示加载状态
            const rewriteBtn = document.getElementById('rewrite-btn');
            const rewriteText = document.getElementById('rewrite-text');
            const rewriteSpinner = document.getElementById('rewrite-spinner');
            
            rewriteText.style.display = 'none';
            rewriteSpinner.style.display = 'inline-block';
            rewriteBtn.disabled = true;
            
            try {
                // 调用DeepSeek API进行降重
                const response = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: systemPrompt
                            },
                            {
                                role: "user",
                                content: `请改写以下段落以降低重复率:\n\n${originalText}`
                            }
                        ],
                        temperature: 0.8,
                        max_tokens: 2000
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 检查响应数据结构
                if (!data.choices || !data.choices[0] || !data.choices[0].message) {
                    throw new Error("API返回的数据格式不正确");
                }
                
                const rewrittenText = data.choices[0].message.content;
                document.getElementById('rewritten-text').value = rewrittenText;
                currentPaperContent = rewrittenText;
                
                // 保存原文和改写后的文本用于比较
                lastOriginalText = originalText;
                lastRewrittenText = rewrittenText;
                
                // 显示预览
                showRewritePreview(originalText, rewrittenText);
                
                // 显示格式化后的论文
                showFormattedPaper(rewrittenText);
            } catch (error) {
                console.error('降重失败:', error);
                alert(`降重失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                rewriteText.style.display = 'inline-block';
                rewriteSpinner.style.display = 'none';
                rewriteBtn.disabled = false;
            }
        }
        
        function showRewritePreview(original, rewritten) {
            const originalPreview = document.getElementById('original-preview');
            const rewrittenPreview = document.getElementById('rewritten-preview');
            
            // 简单高亮处理
            originalPreview.innerHTML = original.replace(/\n/g, '<br>')
                .replace(/([\u4e00-\u9fa5]+)/g, '<span class="highlight-original">$1</span>');
            
            rewrittenPreview.innerHTML = rewritten.replace(/\n/g, '<br>')
                .replace(/([\u4e00-\u9fa5]+)/g, '<span class="highlight-rewritten">$1</span>');
            
            document.getElementById('rewrite-preview').style.display = 'flex';
            document.getElementById('rewrite-diff').style.display = 'none';
        }
        
        function showRewriteDiff() {
            if (!lastOriginalText || !lastRewrittenText) {
                alert('请先进行降重操作');
                return;
            }
            
            const diffContent = document.getElementById('diff-content');
            diffContent.innerHTML = '';
            
            // 简单的逐行比较
            const originalLines = lastOriginalText.split('\n');
            const rewrittenLines = lastRewrittenText.split('\n');
            
            const maxLines = Math.max(originalLines.length, rewrittenLines.length);
            
            for (let i = 0; i < maxLines; i++) {
                const originalLine = originalLines[i] || '';
                const rewrittenLine = rewrittenLines[i] || '';
                
                if (originalLine === rewrittenLine) {
                    // 未改变的行
                    const lineDiv = document.createElement('div');
                    lineDiv.className = 'diff-line diff-unchanged';
                    lineDiv.textContent = originalLine;
                    diffContent.appendChild(lineDiv);
                } else {
                    // 删除的行
                    if (originalLine) {
                        const lineDiv = document.createElement('div');
                        lineDiv.className = 'diff-line diff-removed';
                        lineDiv.textContent = '- ' + originalLine;
                        diffContent.appendChild(lineDiv);
                    }
                    
                    // 新增的行
                    if (rewrittenLine) {
                        const lineDiv = document.createElement('div');
                        lineDiv.className = 'diff-line diff-added';
                        lineDiv.textContent = '+ ' + rewrittenLine;
                        diffContent.appendChild(lineDiv);
                    }
                }
            }
            
            document.getElementById('rewrite-preview').style.display = 'none';
            document.getElementById('rewrite-diff').style.display = 'block';
        }
        
        function copyRewrittenText() {
            const rewrittenText = document.getElementById('rewritten-text');
            if (!rewrittenText.value.trim()) {
                alert('没有可复制的内容');
                return;
            }
            
            rewrittenText.select();
            document.execCommand('copy');
            alert('已复制到剪贴板');
        }
        
        function clearRewriteText() {
            document.getElementById('original-text').value = '';
            document.getElementById('rewritten-text').value = '';
            document.getElementById('rewrite-preview').style.display = 'none';
            document.getElementById('rewrite-diff').style.display = 'none';
            currentPaperContent = "";
            document.getElementById('paper-preview-section').style.display = 'none';
            lastOriginalText = "";
            lastRewrittenText = "";
        }
        
        // ========== 论文润色功能 ==========
        function getStyleDescription(style) {
            const styles = {
                'academic': '学术严谨',
                'concise': '简洁明了',
                'formal': '正式专业',
                'fluent': '流畅自然'
            };
            return styles[style] || '学术严谨';
        }
        
        function getAudienceDescription(audience) {
            const audiences = {
                'general': '普通读者',
                'expert': '领域专家',
                'international': '国际读者'
            };
            return audiences[audience] || '普通读者';
        }
        
        async function polishText() {
            const originalText = document.getElementById('original-text-polish').value.trim();
            if (!originalText) {
                alert('请输入需要润色的文本');
                return;
            }
            
            const style = document.getElementById('polish-style').value;
            const audience = document.getElementById('polish-audience').value;
            const field = document.getElementById('polish-field').value;
            
            // 显示加载状态
            const polishBtn = document.getElementById('polish-btn');
            const polishText = document.getElementById('polish-text');
            const polishSpinner = document.getElementById('polish-spinner');
            
            polishText.style.display = 'none';
            polishSpinner.style.display = 'inline-block';
            polishBtn.disabled = true;
            
            try {
                // 调用DeepSeek API进行润色
                const response = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: `你是一个专业的论文润色专家，需要将用户提供的论文段落进行润色提升。润色风格为${getStyleDescription(style)}，目标读者是${getAudienceDescription(audience)}，学科领域是${getFieldDescription(field)}。请在不改变原意的前提下，提升文本的学术性、流畅性和专业性。`
                            },
                            {
                                role: "user",
                                content: `请润色以下段落:\n\n${originalText}`
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 2000
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 检查响应数据结构
                if (!data.choices || !data.choices[0] || !data.choices[0].message) {
                    throw new Error("API返回的数据格式不正确");
                }
                
                const polishedContent = data.choices[0].message.content;
                document.getElementById('polished-text').value = polishedContent;
                currentPaperContent = polishedContent;
                
                // 获取润色建议
                const suggestionResponse = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: "你是一个专业的论文写作指导老师，需要为用户提供详细的润色建议，解释你做了哪些修改以及为什么这样做。"
                            },
                            {
                                role: "user",
                                content: `请解释你对以下段落的润色:\n\n原文:\n${originalText}\n\n润色后:\n${polishedContent}`
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 1000
                    })
                });
                
                if (!suggestionResponse.ok) {
                    throw new Error(`建议请求失败: ${suggestionResponse.status} ${suggestionResponse.statusText}`);
                }
                
                const suggestionData = await suggestionResponse.json();
                
                // 检查建议响应数据结构
                if (!suggestionData.choices || !suggestionData.choices[0] || !suggestionData.choices[0].message) {
                    throw new Error("建议API返回的数据格式不正确");
                }
                
                document.getElementById('suggestions-content').innerHTML = 
                    suggestionData.choices[0].message.content.replace(/\n/g, '<br>');
                document.getElementById('polish-suggestions').style.display = 'block';
                
                // 显示格式化后的论文
                showFormattedPaper(polishedContent);
            } catch (error) {
                console.error('润色失败:', error);
                alert(`润色失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                polishText.style.display = 'inline-block';
                polishSpinner.style.display = 'none';
                polishBtn.disabled = false;
            }
        }
        
        function copyPolishedText() {
            const polishedText = document.getElementById('polished-text');
            if (!polishedText.value.trim()) {
                alert('没有可复制的内容');
                return;
            }
            
            polishedText.select();
            document.execCommand('copy');
            alert('已复制到剪贴板');
        }
        
        function clearPolishText() {
            document.getElementById('original-text-polish').value = '';
            document.getElementById('polished-text').value = '';
            document.getElementById('polish-suggestions').style.display = 'none';
            currentPaperContent = "";
            document.getElementById('paper-preview-section').style.display = 'none';
        }
        
        // ========== 开题报告功能 ==========
        async function generateProposal() {
            const title = document.getElementById('proposal-title').value.trim();
            const author = document.getElementById('proposal-author').value.trim();
            const school = document.getElementById('proposal-school').value.trim();
            const major = document.getElementById('proposal-major').value.trim();
            const supervisor = document.getElementById('proposal-supervisor').value.trim();
            const date = document.getElementById('proposal-date').value;
            const background = document.getElementById('proposal-background').value.trim();
            const objective = document.getElementById('proposal-objective').value.trim();
            const content = document.getElementById('proposal-content').value.trim();
            const innovation = document.getElementById('proposal-innovation').value.trim();
            const method = document.getElementById('proposal-method').value.trim();
            const plan = document.getElementById('proposal-plan').value.trim();
            const reference = document.getElementById('proposal-reference').value.trim();
            
            if (!title) {
                alert('请输入论文题目');
                return;
            }
            
            // 显示加载状态
            const proposalBtn = document.getElementById('generate-proposal-btn');
            const proposalText = document.getElementById('proposal-text');
            const proposalSpinner = document.getElementById('proposal-spinner');
            
            proposalText.style.display = 'none';
            proposalSpinner.style.display = 'inline-block';
            proposalBtn.disabled = true;
            
            try {
                // 调用DeepSeek API生成开题报告
                const response = await fetch(DEEPSEEK_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [
                            {
                                role: "system",
                                content: "你是一个专业的学术导师，需要根据用户提供的信息生成完整的开题报告。报告应包括标题、基本信息、研究背景与意义、研究目标、研究内容、创新点、研究方法与技术路线、研究计划、参考文献等部分。请使用规范的学术语言和格式。"
                            },
                            {
                                role: "user",
                                content: `请根据以下信息生成开题报告：
                                
论文题目: ${title}
作者: ${author}
学校/机构: ${school}
专业方向: ${major}
指导教师: ${supervisor}
预计完成日期: ${date}

研究背景与意义: ${background}
研究目标: ${objective}
研究内容: ${content}
创新点: ${innovation}
研究方法: ${method}
研究计划: ${plan}
参考文献: ${reference}
                                `
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 2000
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // 检查响应数据结构
                if (!data.choices || !data.choices[0] || !data.choices[0].message) {
                    throw new Error("API返回的数据格式不正确");
                }
                
                const proposalContent = data.choices[0].message.content;
                document.getElementById('proposal-content-result').innerHTML = proposalContent.replace(/\n/g, '<br>');
                document.getElementById('proposal-result').style.display = 'block';
                
                // 保存内容用于导出
                currentPaperContent = proposalContent;
                
                // 滚动到结果区域
                document.getElementById('proposal-result').scrollIntoView({ behavior: 'smooth' });
            } catch (error) {
                console.error('生成开题报告失败:', error);
                alert(`生成开题报告失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                proposalText.style.display = 'inline-block';
                proposalSpinner.style.display = 'none';
                proposalBtn.disabled = false;
            }
        }
        
        function clearProposalForm() {
            document.getElementById('proposal-title').value = '';
            document.getElementById('proposal-author').value = '';
            document.getElementById('proposal-school').value = '';
            document.getElementById('proposal-major').value = '';
            document.getElementById('proposal-supervisor').value = '';
            document.getElementById('proposal-date').value = '';
            document.getElementById('proposal-background').value = '';
            document.getElementById('proposal-objective').value = '';
            document.getElementById('proposal-content').value = '';
            document.getElementById('proposal-innovation').value = '';
            document.getElementById('proposal-method').value = '';
            document.getElementById('proposal-plan').value = '';
            document.getElementById('proposal-reference').value = '';
            document.getElementById('proposal-result').style.display = 'none';
        }
        
        function exportProposalAsDOCX() {
            if (!currentPaperContent) {
                alert('请先生成开题报告');
                return;
            }
            
            // 使用主导出函数
            exportAsDOCX();
        }
        
        // ========== 文献管理功能 ==========
        async function searchReferences() {
            const query = document.getElementById('reference-search').value.trim();
            const database = document.getElementById('reference-database').value;
            
            if (!query) {
                alert('请输入搜索关键词');
                return;
            }
            
            // 显示加载状态
            const searchBtn = document.getElementById('search-reference-btn');
            searchBtn.disabled = true;
            searchBtn.innerHTML = '<i class="bi bi-hourglass"></i> 搜索中...';
            
            const resultsContainer = document.getElementById('reference-search-results');
            resultsContainer.innerHTML = '<p class="text-muted">正在搜索文献，请稍候...</p>';
            
            try {
                let results = [];
                
                if (database === 'crossref') {
                    results = await searchCrossRef(query);
                } else if (database === 'google-scholar') {
                    results = await searchGoogleScholar(query);
                } else if (database === 'pubmed') {
                    results = await searchPubMed(query);
                }
                
                // 显示搜索结果
                if (results.length === 0) {
                    resultsContainer.innerHTML = '<p class="text-muted">没有找到相关文献</p>';
                    return;
                }
                
                resultsContainer.innerHTML = '';
                
                results.forEach((ref, index) => {
                    const refDiv = document.createElement('div');
                    refDiv.className = 'reference-item fade-in';
                    refDiv.id = `ref-${index}`;
                    
                    let authors = ref.authors ? ref.authors.join(', ') : '未知作者';
                    if (authors.length > 50) {
                        authors = authors.substring(0, 50) + '...';
                    }
                    
                    let title = ref.title || '无标题';
                    if (title.length > 100) {
                        title = title.substring(0, 100) + '...';
                    }
                    
                    refDiv.innerHTML = `
                        <h6>${title}</h6>
                        <p class="mb-1">作者: ${authors}</p>
                        <p class="mb-1">来源: ${ref.source || '未知'} (${ref.year || '未知年份'})</p>
                        ${ref.doi ? `<p class="mb-1">DOI: <a href="https://doi.org/${ref.doi}" target="_blank" class="doi-link">${ref.doi}</a></p>` : ''}
                        <button class="btn btn-sm btn-primary verify-btn" onclick="verifyReference('ref-${index}')">
                            <i class="bi bi-check-circle"></i> 验证
                        </button>
                        <button class="btn btn-sm btn-success verify-btn" onclick="addToLibrary('ref-${index}')">
                            <i class="bi bi-plus-circle"></i> 添加到文献库
                        </button>
                    `;
                    
                    // 保存引用数据
                    refDiv.dataset.reference = JSON.stringify(ref);
                    
                    resultsContainer.appendChild(refDiv);
                });
            } catch (error) {
                console.error('搜索文献失败:', error);
                resultsContainer.innerHTML = `<p class="text-danger">搜索失败: ${error.message}</p>`;
            } finally {
                searchBtn.disabled = false;
                searchBtn.innerHTML = '<i class="bi bi-search"></i> 搜索';
            }
        }
        
        async function searchCrossRef(query) {
            const response = await fetch(`${CROSSREF_API_URL}?query=${encodeURIComponent(query)}&rows=10`);
            
            if (!response.ok) {
                throw new Error(`CrossRef API请求失败: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (!data.message || !data.message.items) {
                throw new Error("CrossRef返回的数据格式不正确");
            }
            
            return data.message.items.map(item => ({
                title: item.title ? item.title[0] : '无标题',
                authors: item.author ? item.author.map(a => `${a.given || ''} ${a.family || ''}`.trim()) : ['未知作者'],
                source: item['container-title'] ? item['container-title'][0] : '未知来源',
                year: item.created ? new Date(item.created['date-parts'][0][0]).getFullYear() : '未知年份',
                doi: item.DOI,
                url: item.URL,
                type: item.type,
                database: 'CrossRef'
            }));
        }
        
        async function searchGoogleScholar(query) {
            // 注意: 实际应用中需要使用Google Scholar API密钥
            const API_KEY = ''; // 这里需要替换为实际的API密钥
            const response = await fetch(`${GOOGLE_SCHOLAR_API_URL}?q=${encodeURIComponent(query)}&api_key=${API_KEY}`);
            
            if (!response.ok) {
                throw new Error(`Google Scholar API请求失败: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (!data.organic_results) {
                throw new Error("Google Scholar返回的数据格式不正确");
            }
            
            return data.organic_results.map(item => ({
                title: item.title,
                authors: item.publication_info.authors ? item.publication_info.authors.map(a => a.name) : ['未知作者'],
                source: item.publication_info.summary || '未知来源',
                year: item.publication_info.year || '未知年份',
                url: item.link,
                database: 'Google Scholar'
            }));
        }
        
        async function searchPubMed(query) {
            // 第一步: 搜索PMID
            const searchResponse = await fetch(`${PUBMED_API_URL}?db=pubmed&term=${encodeURIComponent(query)}&retmax=10&retmode=json`);
            
            if (!searchResponse.ok) {
                throw new Error(`PubMed搜索请求失败: ${searchResponse.status} ${searchResponse.statusText}`);
            }
            
            const searchData = await searchResponse.json();
            
            if (!searchData.esearchresult || !searchData.esearchresult.idlist) {
                throw new Error("PubMed返回的搜索数据格式不正确");
            }
            
            const pmids = searchData.esearchresult.idlist;
            
            if (pmids.length === 0) {
                return [];
            }
            
            // 第二步: 获取摘要信息
            const summaryResponse = await fetch(`${PUBMED_SUMMARY_URL}?db=pubmed&id=${pmids.join(',')}&retmode=json`);
            
            if (!summaryResponse.ok) {
                throw new Error(`PubMed摘要请求失败: ${summaryResponse.status} ${summaryResponse.statusText}`);
            }
            
            const summaryData = await summaryResponse.json();
            
            if (!summaryData.result || !summaryData.result.uids) {
                throw new Error("PubMed返回的摘要数据格式不正确");
            }
            
            return pmids.map(pmid => {
                const article = summaryData.result[pmid];
                return {
                    title: article.title || '无标题',
                    authors: article.authors ? article.authors.map(a => a.name) : ['未知作者'],
                    source: article.source || '未知来源',
                    year: article.pubdate ? article.pubdate.substring(0, 4) : '未知年份',
                    doi: article.articleids ? article.articleids.find(id => id.idtype === 'doi')?.value : null,
                    url: `https://pubmed.ncbi.nlm.nih.gov/${pmid}/`,
                    database: 'PubMed'
                };
            });
        }
        
        async function verifyReference(refId) {
            const refDiv = document.getElementById(refId);
            if (!refDiv) return;
            
            const ref = JSON.parse(refDiv.dataset.reference);
            const verifyBtn = refDiv.querySelector('.verify-btn');
            
            verifyBtn.disabled = true;
            verifyBtn.innerHTML = '<i class="bi bi-hourglass"></i> 验证中...';
            
            try {
                // 检查DOI是否存在
                if (ref.doi) {
                    const response = await fetch(`https://doi.org/${ref.doi}`, {
                        method: 'HEAD',
                        redirect: 'manual'
                    });
                    
                    if (response.status === 302 || response.status === 301) {
                        refDiv.classList.add('verified');
                        refDiv.classList.remove('unverified');
                        verifyBtn.innerHTML = '<i class="bi bi-check-circle-fill"></i> 已验证';
                    } else {
                        refDiv.classList.add('unverified');
                        refDiv.classList.remove('verified');
                        verifyBtn.innerHTML = '<i class="bi bi-exclamation-circle-fill"></i> 验证失败';
                    }
                } else {
                    // 如果没有DOI，尝试其他验证方式
                    if (ref.url) {
                        const response = await fetch(ref.url, {
                            method: 'HEAD',
                            redirect: 'manual'
                        });
                        
                        if (response.status === 200 || response.status === 302 || response.status === 301) {
                            refDiv.classList.add('verified');
                            refDiv.classList.remove('unverified');
                            verifyBtn.innerHTML = '<i class="bi bi-check-circle-fill"></i> 已验证';
                        } else {
                            refDiv.classList.add('unverified');
                            refDiv.classList.remove('verified');
                            verifyBtn.innerHTML = '<i class="bi bi-exclamation-circle-fill"></i> 验证失败';
                        }
                    } else {
                        refDiv.classList.add('unverified');
                        refDiv.classList.remove('verified');
                        verifyBtn.innerHTML = '<i class="bi bi-exclamation-circle-fill"></i> 无法验证';
                    }
                }
            } catch (error) {
                console.error('验证文献失败:', error);
                refDiv.classList.add('unverified');
                refDiv.classList.remove('verified');
                verifyBtn.innerHTML = '<i class="bi bi-exclamation-circle-fill"></i> 验证错误';
            } finally {
                verifyBtn.disabled = false;
            }
        }
        
        function addToLibrary(refId) {
            const refDiv = document.getElementById(refId);
            if (!refDiv) return;
            
            const ref = JSON.parse(refDiv.dataset.reference);
            
            // 检查是否已存在
            if (references.some(r => r.doi === ref.doi || r.title === ref.title)) {
                alert('该文献已存在于您的文献库中');
                return;
            }
            
            references.push(ref);
            updateReferenceLibrary();
            
            // 高亮显示已添加
            const addBtn = refDiv.querySelectorAll('.verify-btn')[1];
            addBtn.disabled = true;
            addBtn.innerHTML = '<i class="bi bi-check-circle-fill"></i> 已添加';
        }
        
        function updateReferenceLibrary() {
            const libraryContainer = document.getElementById('reference-library');
            
            if (references.length === 0) {
                libraryContainer.innerHTML = '<p class="text-muted">您添加的文献将显示在这里</p>';
                return;
            }
            
            libraryContainer.innerHTML = '';
            
            references.forEach((ref, index) => {
                const refDiv = document.createElement('div');
                refDiv.className = 'reference-item verified fade-in';
                
                let authors = ref.authors ? ref.authors.join(', ') : '未知作者';
                if (authors.length > 50) {
                    authors = authors.substring(0, 50) + '...';
                }
                
                let title = ref.title || '无标题';
                if (title.length > 100) {
                    title = title.substring(0, 100) + '...';
                }
                
                refDiv.innerHTML = `
                    <h6>${title}</h6>
                    <p class="mb-1">作者: ${authors}</p>
                    <p class="mb-1">来源: ${ref.source || '未知'} (${ref.year || '未知年份'})</p>
                    ${ref.doi ? `<p class="mb-1">DOI: <a href="https://doi.org/${ref.doi}" target="_blank" class="doi-link">${ref.doi}</a></p>` : ''}
                    <span class="badge bg-secondary source-badge">${ref.database || '未知数据库'}</span>
                    <button class="btn btn-sm btn-danger verify-btn" onclick="removeReference(${index})">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                `;
                
                libraryContainer.appendChild(refDiv);
            });
        }
        
        function removeReference(index) {
            if (confirm('确定要从文献库中删除这条文献吗？')) {
                references.splice(index, 1);
                updateReferenceLibrary();
            }
        }
        
        function exportReferences() {
            if (references.length === 0) {
                alert('文献库中没有文献可导出');
                return;
            }
            
            const style = document.getElementById('reference-style').value;
            let formattedRefs = [];
            
            references.forEach(ref => {
                let formattedRef = '';
                
                switch(style) {
                    case 'apa':
                        formattedRef = formatAPACitation(ref);
                        break;
                    case 'mla':
                        formattedRef = formatMLACitation(ref);
                        break;
                    case 'chicago':
                        formattedRef = formatChicagoCitation(ref);
                        break;
                    case 'gb':
                        formattedRef = formatGBCitation(ref);
                        break;
                    default:
                        formattedRef = formatAPACitation(ref);
                }
                
                formattedRefs.push(formattedRef);
            });
            
            const refText = formattedRefs.join('\n\n');
            const blob = new Blob([refText], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'references.txt';
            a.click();
            URL.revokeObjectURL(url);
        }
        
        function formatAPACitation(ref) {
            let authors = ref.authors ? ref.authors.join(', ') : '未知作者';
            let year = ref.year || 'n.d.';
            let title = ref.title || '无标题';
            let source = ref.source || '未知来源';
            
            return `${authors}. (${year}). ${title}. ${source}.${ref.doi ? ` https://doi.org/${ref.doi}` : ''}`;
        }
        
        function formatMLACitation(ref) {
            let authors = ref.authors ? ref.authors.join(', ') : '未知作者';
            let title = ref.title || '无标题';
            let source = ref.source || '未知来源';
            let year = ref.year || 'n.d.';
            
            return `${authors}. "${title}." ${source}, ${year}.${ref.doi ? ` DOI: ${ref.doi}` : ''}`;
        }
        
        function formatChicagoCitation(ref) {
            let authors = ref.authors ? ref.authors.join(', ') : '未知作者';
            let year = ref.year || 'n.d.';
            let title = ref.title || '无标题';
            let source = ref.source || '未知来源';
            
            return `${authors}. ${year}. "${title}." ${source}.${ref.doi ? ` https://doi.org/${ref.doi}` : ''}`;
        }
        
        function formatGBCitation(ref) {
            let authors = ref.authors ? ref.authors.join(', ') : '未知作者';
            let title = ref.title || '无标题';
            let source = ref.source || '未知来源';
            let year = ref.year || '出版年份不详';
            
            return `${authors}. ${title}[J]. ${source}, ${year}.${ref.doi ? ` DOI:${ref.doi}` : ''}`;
        }
        
        function clearReferences() {
            if (confirm('确定要清空文献库吗？此操作不可撤销。')) {
                references = [];
                updateReferenceLibrary();
            }
        }
        
        // ========== 论文格式化与导出功能 ==========
        function formatPaperContent(content) {
            // 修复中文乱码问题
            content = content.replace(/[^\x00-\x7F]/g, function(c) {
                return c;
            });
            
            // 智能识别标题并加粗换行
            content = content.replace(/(\n|^)([一二三四五六七八九十]+、|[1-9][0-9]*\.|[1-9][0-9]*、)/g, '$1\n**$2**');
            content = content.replace(/(\n|^)(第[一二三四五六七八九十]+章|摘要|引言|结论|参考文献)/g, '$1\n## $2');
            content = content.replace(/(\n|^)([1-9][0-9]*\.[1-9][0-9]*)/g, '$1\n**$2**');
            
            // 处理表格 - 转换为三线表格式
            content = content.replace(/(\n\s*\|.+\|\s*\n\s*\|[-|:\s]+\|\s*\n)((?:\s*\|.+\|\s*\n)+)/g, function(match, header, rows) {
                // 检查是否是空表格
                if (rows.trim().split('\n').every(row => row.replace(/\|/g, '').trim() === '')) {
                    return ''; // 删除空表格
                }
                
                let table = '<table>\n<caption>表格标题</caption>\n<thead>\n<tr>\n';
                
                // 处理表头
                const headers = header.split('|').slice(1, -1).map(h => h.trim());
                headers.forEach(h => {
                    table += `<th>${h}</th>\n`;
                });
                
                table += '</tr>\n</thead>\n<tbody>\n';
                
                // 处理行
                const rowLines = rows.trim().split('\n');
                rowLines.forEach(line => {
                    const cells = line.split('|').slice(1, -1).map(c => c.trim());
                    // 检查是否是空行
                    if (cells.some(cell => cell.trim() !== '')) {
                        table += '<tr>\n';
                        cells.forEach(c => {
                            table += `<td>${c}</td>\n`;
                        });
                        table += '</tr>\n';
                    }
                });
                
                table += '</tbody>\n</table>\n';
                return table;
            });
            
            // 处理图表
            content = content.replace(/\[图(\d+):(.+?)\]/g, '\n<div class="paper-figure">\n  <div class="paper-figure-caption">图$1: $2</div>\n</div>\n');
            content = content.replace(/\[表(\d+):(.+?)\]/g, '\n<div class="paper-figure">\n  <div class="paper-figure-caption">表$1: $2</div>\n</div>\n');
            
            // 处理特殊符号和字母
            content = content.replace(/([a-zA-Z])([a-zA-Z]+)/g, function(match, p1, p2) {
                // 保持专有名词大小写不变
                if (p1 === p1.toUpperCase() && p2 === p2.toUpperCase()) {
                    return match;
                }
                return p1 + p2.toLowerCase();
            });
            
            // 处理段落
            content = content.replace(/\n\s*\n/g, '\n\n');
            
            return content;
        }
        
        // 显示格式化后的论文
        function showFormattedPaper(content) {
            const formattedContent = formatPaperContent(content);
            const formattedPaper = document.getElementById('formatted-paper');
            
            // 清空并重新构建预览区域
            formattedPaper.innerHTML = '';
            
            // 分割内容为不同部分
            const sections = formattedContent.split(/\n##\s+/);
            
            // 处理标题，确保不重复
            let hasTitle = false;
            let previousSections = new Set();
            
            sections.forEach((section, index) => {
                if (!section.trim()) return;
                
                const sectionDiv = document.createElement('div');
                sectionDiv.className = 'paper-section fade-in';
                
                // 第一个部分是标题
                if (index === 0 && !hasTitle) {
                    const titleMatch = section.match(/^(.*?)\n/);
                    if (titleMatch) {
                        const titleDiv = document.createElement('div');
                        titleDiv.className = 'paper-title';
                        titleDiv.textContent = titleMatch[1];
                        sectionDiv.appendChild(titleDiv);
                        hasTitle = true;
                        
                        // 剩余内容作为摘要或其他内容
                        const restContent = section.substring(titleMatch[0].length);
                        if (restContent.trim()) {
                            const contentDiv = document.createElement('div');
                            contentDiv.innerHTML = marked.parse(restContent);
                            sectionDiv.appendChild(contentDiv);
                        }
                    } else {
                        sectionDiv.innerHTML = marked.parse(section);
                    }
                } else {
                    // 其他部分是各个章节
                    const sectionTitle = section.split('\n')[0];
                    const sectionContent = section.substring(sectionTitle.length);
                    
                    // 跳过重复的标题
                    if (!previousSections.has(sectionTitle) && sectionTitle !== '标题' && sectionTitle !== '摘要') {
                        previousSections.add(sectionTitle);
                        
                        const titleElement = document.createElement('h2');
                        titleElement.textContent = sectionTitle;
                        sectionDiv.appendChild(titleElement);
                    }
                    
                    if (sectionContent.trim()) {
                        const contentDiv = document.createElement('div');
                        contentDiv.innerHTML = marked.parse(sectionContent);
                        sectionDiv.appendChild(contentDiv);
                    }
                }
                
                formattedPaper.appendChild(sectionDiv);
            });
            
            document.getElementById('paper-preview-section').style.display = 'block';
        }
        
        // 导出为Word文档 - 使用docx.js
        async function exportAsDOCX() {
            if (isExporting) return;
            isExporting = true;
            
            try {
                // 显示导出进度条
                const exportProgress = document.getElementById('export-progress');
                const exportProgressText = document.getElementById('export-progress-text');
                const exportProgressFill = document.getElementById('export-progress-fill');
                
                exportProgress.style.display = 'flex';
                exportProgressText.textContent = '准备导出内容...';
                exportProgressFill.style.width = '0%';
                
                // 禁用所有导出按钮
                const originalButtons = document.querySelectorAll('.export-buttons button');
                originalButtons.forEach(btn => {
                    btn.disabled = true;
                    btn.innerHTML = '<i class="bi bi-hourglass"></i> 处理中...';
                });
                
                // 创建Word文档
                const { Document, Paragraph, TextRun, HeadingLevel, AlignmentType, Table, TableRow, TableCell, WidthType } = docx;
                
                // 获取格式化后的论文内容
                const paperContent = document.getElementById('formatted-paper').cloneNode(true);
                
                // 更新进度
                exportProgressText.textContent = '正在处理文档结构...';
                exportProgressFill.style.width = '20%';
                
                // 准备文档内容
                const docChildren = [];
                
                // 处理标题
                const titleElement = paperContent.querySelector('.paper-title');
                if (titleElement) {
                    docChildren.push(
                        new Paragraph({
                            text: titleElement.textContent,
                            heading: HeadingLevel.HEADING_1,
                            alignment: AlignmentType.CENTER,
                            spacing: { after: 200 }
                        })
                    );
                }
                
                // 处理作者信息
                const authorElement = paperContent.querySelector('.paper-author');
                if (authorElement) {
                    docChildren.push(
                        new Paragraph({
                            text: authorElement.textContent,
                            alignment: AlignmentType.CENTER,
                            spacing: { after: 300 }
                        })
                    );
                }
                
                // 处理各个章节
                const sections = paperContent.querySelectorAll('.paper-section');
                
                sections.forEach((section, index) => {
                    // 跳过已经处理过的标题和作者
                    if (index === 0 && (titleElement || authorElement)) return;
                    
                    // 处理章节标题
                    const headings = section.querySelectorAll('h1, h2, h3, h4, h5, h6');
                    
                    headings.forEach(heading => {
                        const level = parseInt(heading.tagName.substring(1));
                        const headingText = heading.textContent.trim();
                        
                        let headingLevel;
                        switch(level) {
                            case 1: headingLevel = HeadingLevel.HEADING_1; break;
                            case 2: headingLevel = HeadingLevel.HEADING_2; break;
                            case 3: headingLevel = HeadingLevel.HEADING_3; break;
                            case 4: headingLevel = HeadingLevel.HEADING_4; break;
                            case 5: headingLevel = HeadingLevel.HEADING_5; break;
                            case 6: headingLevel = HeadingLevel.HEADING_6; break;
                            default: headingLevel = HeadingLevel.HEADING_2;
                        }
                        
                        docChildren.push(
                            new Paragraph({
                                text: headingText,
                                heading: headingLevel,
                                spacing: { before: 400, after: 200 }
                            })
                        );
                    });
                    
                    // 处理段落
                    const paragraphs = section.querySelectorAll('p:not(.paper-author):not(.paper-keywords)');
                    
                    paragraphs.forEach(p => {
                        const paragraphText = p.textContent.trim();
                        if (paragraphText) {
                            docChildren.push(
                                new Paragraph({
                                    children: [new TextRun({ text: paragraphText })],
                                    indent: { firstLine: 600 }, // 首行缩进2字符
                                    spacing: { line: 360 }, // 1.5倍行距
                                })
                            );
                        }
                    });
                    
                    // 处理表格
                    const tables = section.querySelectorAll('table');
                    
                    tables.forEach(table => {
                        const tableRows = [];
                        
                        // 处理表头
                        const headerRow = table.querySelector('thead tr');
                        if (headerRow) {
                            const cells = headerRow.querySelectorAll('th');
                            const tableRow = new TableRow({
                                children: Array.from(cells).map(cell => 
                                    new TableCell({
                                        children: [new Paragraph({ text: cell.textContent.trim() })],
                                        margins: { top: 100, bottom: 100, left: 100, right: 100 }
                                    })
                                )
                            });
                            tableRows.push(tableRow);
                        }
                        
                        // 处理表格内容
                        const bodyRows = table.querySelectorAll('tbody tr');
                        
                        bodyRows.forEach(row => {
                            const cells = row.querySelectorAll('td');
                            const tableRow = new TableRow({
                                children: Array.from(cells).map(cell => 
                                    new TableCell({
                                        children: [new Paragraph({ text: cell.textContent.trim() })],
                                        margins: { top: 100, bottom: 100, left: 100, right: 100 }
                                    })
                                )
                            });
                            tableRows.push(tableRow);
                        });
                        
                        docChildren.push(
                            new Table({
                                rows: tableRows,
                                width: { size: 100, type: WidthType.PERCENTAGE },
                                margins: { top: 200, bottom: 200 }
                            })
                        );
                    });
                    
                    // 处理图表
                    const figures = section.querySelectorAll('.paper-figure');
                    
                    figures.forEach(figure => {
                        const caption = figure.querySelector('.paper-figure-caption');
                        if (caption) {
                            docChildren.push(
                                new Paragraph({
                                    text: caption.textContent.trim(),
                                    alignment: AlignmentType.CENTER,
                                    italics: true,
                                    spacing: { before: 200, after: 200 }
                                })
                            );
                        }
                    });
                    
                    // 更新进度
                    exportProgressFill.style.width = `${20 + Math.floor((index / sections.length) * 70)}%`;
                });
                
                // 更新进度
                exportProgressText.textContent = '正在生成Word文档...';
                exportProgressFill.style.width = '90%';
                
                // 创建文档
                const doc = new Document({
                    styles: {
                        paragraphStyles: [
                            {
                                id: "Normal",
                                name: "Normal",
                                run: {
                                    font: "Times New Roman",
                                    size: 24, // 12pt
                                },
                                paragraph: {
                                    spacing: { line: 360 }, // 1.5倍行距
                                }
                            },
                            {
                                id: "Heading1",
                                name: "Heading 1",
                                basedOn: "Normal",
                                next: "Normal",
                                run: {
                                    bold: true,
                                    size: 32, // 16pt
                                },
                                paragraph: {
                                    spacing: { before: 400, after: 200 },
                                    alignment: AlignmentType.CENTER
                                }
                            },
                            {
                                id: "Heading2",
                                name: "Heading 2",
                                basedOn: "Normal",
                                next: "Normal",
                                run: {
                                    bold: true,
                                    size: 28, // 14pt
                                },
                                paragraph: {
                                    spacing: { before: 300, after: 150 },
                                    indent: { left: 0 }
                                }
                            }
                        ]
                    },
                    sections: [{
                        properties: {},
                        children: docChildren
                    }]
                });
                
                // 更新进度
                exportProgressText.textContent = '正在保存文档...';
                exportProgressFill.style.width = '95%';
                
                // 导出文档
                const blob = await docx.Packer.toBlob(doc);
                saveAs(blob, "论文.docx");
                
                // 更新进度
                exportProgressText.textContent = '导出完成！';
                exportProgressFill.style.width = '100%';
                
                // 恢复按钮状态
                originalButtons.forEach(btn => {
                    btn.disabled = false;
                    if (btn.textContent.includes('Word')) {
                        btn.innerHTML = '<i class="bi bi-file-earmark-word"></i> 导出Word';
                    }
                });
                
                // 隐藏进度条
                setTimeout(() => {
                    exportProgress.style.display = 'none';
                }, 1000);
            } catch (error) {
                console.error('导出Word失败:', error);
                alert(`导出Word失败: ${error.message}`);
                
                // 恢复按钮状态
                const buttons = document.querySelectorAll('.export-buttons button');
                buttons.forEach(btn => {
                    btn.disabled = false;
                    if (btn.textContent.includes('Word')) {
                        btn.innerHTML = '<i class="bi bi-file-earmark-word"></i> 导出Word';
                    }
                });
                
                // 隐藏进度条
                document.getElementById('export-progress').style.display = 'none';
            } finally {
                isExporting = false;
            }
        }
        
        // 复制到剪贴板
        function copyToClipboard() {
            if (isExporting) return;
            
            try {
                const content = document.getElementById('formatted-paper').innerText;
                navigator.clipboard.writeText(content).then(() => {
                    alert('论文内容已复制到剪贴板！');
                });
            } catch (error) {
                console.error('复制失败:', error);
                alert(`复制失败: ${error.message}`);
            }
        }
        
        // 初始化渲染
        document.addEventListener('DOMContentLoaded', function() {
            renderChat();
            
            // 配置marked.js以正确处理中文和表格
            marked.setOptions({
                breaks: true,
                gfm: true,
                langPrefix: 'language-',
                smartypants: true,
                xhtml: true
            });
            
            // 从localStorage加载文献库
            if (localStorage.getItem('references')) {
                references = JSON.parse(localStorage.getItem('references'));
                updateReferenceLibrary();
            }
            
            // 保存文献库到localStorage
            window.addEventListener('beforeunload', function() {
                localStorage.setItem('references', JSON.stringify(references));
            });
        });
    </script>
</body>
</html>